package project.order.work;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import net.sf.json.JSONObject;

public class AccessTokenThread extends Thread {
    static private AccessTokenThread accessTokenThread;
    static {
        accessTokenThread=new AccessTokenThread();
        accessTokenThread.start();
    }
    
    
    static public String access_token=null;
    static public String jsapi_ticket = null;
     static public String appid="wx6e3f16241d2c490d";
     static public String secret="d1267480c86e9fced2e14c2d76bbf5c1";
    static public long refreshTime = 0;
    public void run() {
        try {
            this.sleep(1000);//先休眠1秒，再取
        }
        catch (Exception ex) {
        }
        while (true) {
            //send to 微信
            try {
                URL url=new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret);
                
                trustAllHttpsCertificates();
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
                
                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setDoOutput(false);
                //获取InputStream的值
                InputStream is=null;
                JSONObject json=null;//初值
                try {
                    is=conn.getInputStream();
                    String sReturn=new String(readInputStream(is),("UTF-8"));
                    System.out.println("AccesTokenThread get winxin Message:"+sReturn);
                    is.close();
                    //获得json对象，catch中的异常也需要使用这个值
                    json=JSONObject.fromObject(sReturn);
                    //设置静态变量
                    access_token=(String) json.get("access_token");
                    refreshTime = new Date().getTime() / 1000;
                    System.out.println("access_token:"+access_token+"-refreshTime:"+refreshTime);
                    //更新js-sdk的票据
                    jsapi_ticket = getJsapi_ticket(access_token);
                }
                catch (Exception ex) {
                    if (json!=null) {
                        System.out.println((Integer) json.get("errcode"));
                        System.out.println((String) json.get("errmsg"));
                        System.out.println("json:"+json.toString());
                    }
                    ex.printStackTrace();
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }

            try {
                System.out.println("Thread sleep ");
                this.sleep(6000000);//应该是： 7200秒小一些，可以用：3000000
                System.out.println("Thread wake up ");
            }
            catch (Exception ex) {
            }

            
        }

    }
    public String getJsapi_ticket(String accessToken){
    	String jsapiTicket = "";
    	 try {
             URL url=new URL("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi");
             
             trustAllHttpsCertificates();
             HttpsURLConnection.setDefaultHostnameVerifier(hv);
             
             HttpURLConnection conn=(HttpURLConnection) url.openConnection();
             conn.setRequestMethod("GET");
             conn.setDoOutput(false);
             //获取InputStream的值
             InputStream is=null;
             JSONObject json=null;//初值
             try {
                 is=conn.getInputStream();
                 String sReturn=new String(readInputStream(is),("UTF-8"));
                 System.out.println("AccesTokenThread get winxin Message:"+sReturn);
                 is.close();
                 //获得json对象，catch中的异常也需要使用这个值
                 json=JSONObject.fromObject(sReturn);
                 //设置静态变量
                 jsapiTicket=(String) json.get("ticket");
                 System.out.println("ticket:"+jsapiTicket);
        
                 
             }
             catch (Exception ex) {
                 if (json!=null) {
                	 System.out.println("ticket:"+jsapiTicket);
                     System.out.println((Integer) json.get("errcode"));
                     System.out.println((String) json.get("errmsg"));
                     System.out.println("json:"+json.toString());
                 }
                 ex.printStackTrace();
             }
         }
         catch (Exception ex) {
             ex.printStackTrace();
         }
    	return jsapiTicket;    	
    }
    public byte[] readInputStream(InputStream inStream){
        byte[] data=null;
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len = inStream.read(buffer)) !=-1 ){
                outStream.write(buffer, 0, len);
            }
            data = outStream.toByteArray();//
            outStream.close();
            inStream.close();

        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return data;
    }
    
    //以下开始时https的信任默认代码
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                               + session.getPeerHost());
            return true;
        }
    };
 
     private static void trustAllHttpsCertificates() throws Exception {
         javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
         javax.net.ssl.TrustManager tm = new Mitm();
         trustAllCerts[0] = tm;
         javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
         sc.init(null, trustAllCerts, null);
         javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
     }
    
     static class Mitm implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
             return null;
         }
    
         public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
             return true;
         }
    
         public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
         }
    
         public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
            return;
         }
    
         public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
             return;
         }
     }
    
    
}